<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\Config;
use App\library\services\ConfigService;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Illuminate\Support\Facades\Redis;

class ConfigController extends AdminController
{
    /**
     * Author:Zhongyuan Lu
     * 配置
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Config(), function (Grid $grid) {
            $grid->column('id')->sortable();
            $grid->column('field_name');        //键
            $grid->column('value');             //值
            $grid->column('desc');              //简介
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');

            });
        });
    }

    /**
     * Author:Zhongyuan Lu
     * 配置详情
     * @param $id
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Config(), function (Show $show) {
            $show->field('id');
            $show->field('field_name');
            $show->field('value');
            $show->field('desc');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Author:Zhongyuan Lu
     * 配置添加
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Config(), function (Form $form) {
            $form->display('id');
            $form->text('field_name');
            $form->text('value');
            $form->text('desc');

            $form->display('created_at');
            $form->display('updated_at');

            //将添加、修改的数据更新到redis中
            $form->saved(function (Form $form, $result) {
                // 自增ID
                if ($form->isCreating()) {
                    $config = ConfigService::getById($result);
                }elseif ($form->isEditing()) {
                    $config = $form->model();
                }

                Redis::select(5);
                Redis::set("config:{$config->field_name}",$config->value);
            });
        });
    }

}
